package com.zmj.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.zmj.base.ExceptionEnum;
import com.zmj.base.Response;
import com.zmj.comon.HttpRemoteClient;
import com.zmj.config.RemoteUrlConfig;
import com.zmj.constants.Constants;
import com.zmj.entity.CylinderTestDataDto;
import com.zmj.entity.FigureDataDto;
import com.zmj.entity.PreDataDto;
import com.zmj.entity.RecordListDataResponse;
import com.zmj.enums.OilcylinderEnum;
import com.zmj.service.DocumentInfoService;
import com.zmj.util.DateUtil;

@Service
public class DocumentInfoServiceImpl implements DocumentInfoService {

    @Autowired
    private HttpRemoteClient httpRemoteClient;

    @Autowired
    private RemoteUrlConfig remoteUrlConfig;

    /** 文档附件在服务器的存储地址 */
    public static final String ACCESSORIES_REMOTE_PATH = "/data/zmj-book/document/accessory/";

    /**
     * 概要
     */
    private static final String LISTGAIYAO = "<div class=\"item-wrap\">\n"
        + "\t\t\t\t<h5 class=\"vice-min-title\">概要</h5>\n" + "\t\t\t\t<table class=\"table\" border=\"0\">\n"
        + "\t\t\t\t\t<tbody>\n" + "\t\t\t\t\t\t<tr>\n" + "\t\t\t\t\t\t\t<td>施工号</td>\n" + "\t\t\t\t\t\t\t<td>%s</td>\n"
        + "\t\t\t\t\t\t\t<td>油缸编号</td>\n" + "\t\t\t\t\t\t\t<td>%s</td>\n" + "\t\t\t\t\t\t</tr>\n" + "\t\t\t\t\t\t<tr>\n"
        + "\t\t\t\t\t\t\t<td>类型</td>\n" + "\t\t\t\t\t\t\t<td>%s</td>\n" + "\t\t\t\t\t\t\t<td>检测结果</td>\n"
        + "\t\t\t\t\t\t\t<td style=\"font-weight: bold;\">%s</td>\n" + "\t\t\t\t\t\t</tr>\n" + "\t\t\t\t\t</tbody>\n"
        + "\t\t\t\t</table>\n" + "\t\t\t</div>";

    /**
     * 检测员
     * 实验时间
     */
    private static final String LISTJIANCE = "<div class=\"tip\">\n" + "\t\t\t\t<p>\n"
        + "\t\t\t\t\t<span>检测员：</span><span>%s</span>\n" + "\t\t\t\t</p>\n" + "\t\t\t\t<p>\n"
        + "\t\t\t\t\t<span>实验时间：</span><span>%s</span>\n" + "\t\t\t\t</p>\n" + "\t\t\t</div>";
    /**
     * 压力数据
     */
    private static final String LISTYALI = "</div>\n" + "\n" + "\t\t<script src=\"static/jquery.min.js\"></script>\n"
        + "\t\t<script src=\"static/echarts.min@4.9.0.js\"></script>\n" + "\t\t<script type=\"text/javascript\">\n"
        + "\t\t\t\n" + "\n" + "\t\t\tfunction echartOption(data) {\n" + "\t\t\t\tconst option = {\n"
        + "\t\t\t\t\tgrid: {\n" + "\t\t\t\t\t\tleft: '4%',\n" + "\t\t\t\t\t\tright: '5%',\n"
        + "\t\t\t\t\t\ttop: '6%',\n" + "\t\t\t\t\t\tbottom: '8%'\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\txAxis: {\n"
        + "\t\t\t\t\t\ttype: 'category',\n" + "\t\t\t\t\t\tdata: data.currentTime,\n" + "\t\t\t\t\t},\n"
        + "\t\t\t\t\tyAxis: {\n" + "\t\t\t\t\t\ttype: 'value',\n" + "\t\t\t\t\t\tmin: 0,\n" + "\t\t\t\t\t\tmax: 80,\n"
        + "\t\t\t\t\t\tsplitNumber: 11\n" + "\t\t\t\t\t},\n" + "\t\t\t\t\tseries: [{\n"
        + "\t\t\t\t\t\t\tsymbol: 'none',\n" + "\t\t\t\t\t\t\tsmooth: true,\n" + "\t\t\t\t\t\t\tdata: data.upPre,\n"
        + "\t\t\t\t\t\t\ttype: 'line'\n" + "\t\t\t\t\t\t},\n" + "\t\t\t\t\t\t{\n" + "\t\t\t\t\t\t\tsymbol: 'none',\n"
        + "\t\t\t\t\t\t\tsmooth: true,\n" + "\t\t\t\t\t\t\tdata: data.downPre,\n" + "\t\t\t\t\t\t\ttype: 'line'\n"
        + "\t\t\t\t\t\t},\n" + "\t\t\t\t\t]\n" + "\t\t\t\t}\n" + "\t\t\t\treturn option\n" + "\t\t\t}\n"
        + "\t\t\tnew Vue({\n" + "\t\t\t\tel: '#app',\n" + "\t\t\t\tdata: {\n" + "\t\t\t\t\tshiGongHao: 200\n"
        + "\t\t\t\t},\n" + "\t\t\t\tmounted() {\n"
        + "\t\t\t\t\tlet preChart = echarts.init(document.getElementById('echart-pre-wrap'));\n"
        + "\t\t\t\t\tlet options = echartOption(\n" + "\t\t\t\t\t\t{\n" + "\t\t\t\t\t\t\tcurrentTime: ,\n"
        + "\t\t\t\t\t\t\tupPre: ,\n" + "\t\t\t\t\t\t\tdownPre: \n" + "\t\t\t\t\t\t}\n"
        + "\t\t\t\t\t)\n" + "\t\t\t\t\twindow.onresize = preChart.resize\n" + "\t\t\t\t\tpreChart.setOption(options)\n"
        + "\t\t\t\t\tthis.shiGongHao = '数据测试'\n" + "\t\t\t\t},\n" + "\t\t\t\tmethods: {}\n" + "\t\t\t})\n" + "\n"
        + "\t\t\t\n" + "\t\t</script>\n" + "\t</body>\n" + "\n" + "</html>";

    /**
     * 最下面表格
     */
    private static final String LISTBIAOGEPRE = "<!-- 折线图 -->\n" + "\t\t\t<div class=\"item-wrap\">\n"
        + "\t\t\t\t<h5 class=\"vice-min-title\">压力数据</h5>\n" + "\t\t\t\t<div class=\"canas-wraper d-flex\">\n"
        + "\t\t\t\t\t<div class=\"pre-canvas\">\n" + "\t\t\t\t\t\t<div id=\"echart-pre-wrap\"></div>\n"
        + "\t\t\t\t\t</div>\n" + "\t\t\t\t</div>\n" + "\t\t\t</div>\n" + "\t\t\t<!-- 结果表格 -->\n"
        + "\t\t\t<div class=\"item-wrap\">\n" + "\t\t\t\t<table class=\"table\" border=\"0\">\n"
        + "\t\t\t\t\t<tbody id=\"pre-table\">\n" + "\t\t\t\t\t\t<tr>\n" + "\t\t\t\t\t\t\t<td>部位</td>\n"
        + "\t\t\t\t\t\t\t<td>压力值（Mpa）</td>\n" + "\t\t\t\t\t\t\t<td>保压时长（s）</td>\n" + "\t\t\t\t\t\t\t<td>压降（Mpa）</td>\n"
        + "\t\t\t\t\t\t</tr>";

    private static final String LISTBIAOGE = "<tr>\n" + "    \t\t\t\t\t\t\t<td>%s</td>\n"
        + "    \t\t\t\t\t\t\t<td>%s</td>\n" + "    \t\t\t\t\t\t\t<td>%s</td>\n" + "    \t\t\t\t\t\t\t<td>%s</td>\n"
        + "    \t\t\t\t\t\t</tr>";

    private static final String LISTBIAOGESUFFIX = "</tbody>\n" + "\t\t\t\t</table>\n" + "\t\t\t</div>";
   /* private static final String LISTBIAOGE = "<!-- 折线图 -->\n" + "\t\t\t<div class=\"item-wrap\">\n"
        + "\t\t\t\t<h5 class=\"vice-min-title\">压力数据</h5>\n" + "\t\t\t\t<div class=\"canas-wraper d-flex\">\n"
        + "\t\t\t\t\t<div class=\"pre-canvas\">\n" + "\t\t\t\t\t\t<div id=\"echart-pre-wrap\"></div>\n"
        + "\t\t\t\t\t</div>\n" + "\t\t\t\t</div>\n" + "\t\t\t</div>\n" + "\t\t\t<!-- 结果表格 -->\n"
        + "\t\t\t<div class=\"item-wrap\">\n" + "\t\t\t\t<table class=\"table\" border=\"0\">\n"
        + "\t\t\t\t\t<tbody id=\"pre-table\">\n" + "\t\t\t\t\t\t<tr>\n" + "\t\t\t\t\t\t\t<td>部位</td>\n"
        + "\t\t\t\t\t\t\t<td>压力值（Mpa）</td>\n" + "\t\t\t\t\t\t\t<td>保压时长（s）</td>\n" + "\t\t\t\t\t\t\t<td>压降（Mpa）</td>\n"
        + "\t\t\t\t\t\t</tr>\n" + "\t\t\t\t\t\t<tr>\n" + "\t\t\t\t\t\t\t<td>活塞杆腔</td>\n"
        + "\t\t\t\t\t\t\t<td>38.5</td>\n" + "\t\t\t\t\t\t\t<td>360</td>\n" + "\t\t\t\t\t\t\t<td>0.05</td>\n"
        + "\t\t\t\t\t\t</tr>\n" + "\t\t\t\t\t\t<tr>\n" + "\t\t\t\t\t\t\t<td>活塞腔</td>\n"
        + "\t\t\t\t\t\t\t<td>39.52</td>\n" + "\t\t\t\t\t\t\t<td>360</td>\n" + "\t\t\t\t\t\t\t<td>0.03</td>\n"
        + "\t\t\t\t\t\t</tr>\n" + "\t\t\t\t\t</tbody>\n" + "\t\t\t\t</table>\n" + "\t\t\t</div>";*/

    @Override
    public void generateSinglehtml() {
        // http://121.89.209.113:8700/pi/api/v1/cylinderPlatform/list/page?pageNum=1&size=1000
        // &macAddress=dc:a6:32:8d:c3:6d&constructionNo=Z20-107&oilCylinderType=5&errorCode=1

        // http://121.89.209.113:8700/pi/api/v1/cylinderPlatform/info?recordId=12604

        String pageNum = "1";
        String size = "1000";
        String macAddress = "dc:a6:32:8d:c3:6d";
        String constructionNo = "Z20-107";
        String oilCylinderType = "5";
        String errorCode = "1";

        Response<PageInfo<CylinderTestDataDto>> returnPage = httpRemoteClient.getForObject(
            remoteUrlConfig.getRemotemanagerhttpurl() + Constants.QUERY_PAGE + "?pageNum=" + pageNum + "&size=" + size
                + "&macAddress=" + macAddress + "&constructionNo=" + constructionNo + "&oilCylinderType="
                + oilCylinderType + "&errorCode=" + errorCode, new HashMap<>(),
            new TypeReference<Response<PageInfo<CylinderTestDataDto>>>() {
            });

        //获取数据
        PageInfo<CylinderTestDataDto> cylinderTestDataDtoPageInfo = returnPage.getBody();
        List<CylinderTestDataDto> cylinderTestDataDtoList = cylinderTestDataDtoPageInfo.getList();
        //遍历数据
        for (CylinderTestDataDto cylinderTestDataDto : cylinderTestDataDtoList) {

            Response<RecordListDataResponse> returnInfo = httpRemoteClient.getForObject(
                remoteUrlConfig.getRemotemanagerhttpurl() + Constants.QUERY_INFO + "?recordId=" + cylinderTestDataDto
                    .getRecordId(), new HashMap<>(), new TypeReference<Response<RecordListDataResponse>>() {
                });

            RecordListDataResponse body = returnInfo.getBody();
            List<FigureDataDto> figureDataList = body.getFigureDataList();
            /** 上腔压力 */
            List<BigDecimal> upPreData = figureDataList.stream().map(FigureDataDto::getUpPre).collect(
                Collectors.toList());
            /** 下腔压力 */
            List<BigDecimal> downPreData = figureDataList.stream().map(FigureDataDto::getDownPre).collect(
                Collectors.toList());
            /** 数据数量 */
            List<BigDecimal> currentTimeData = figureDataList.stream().map(FigureDataDto::getCurrentTime).collect(
                Collectors.toList());


            // String  strA="天冷了多穿点";
            // String  strB=strA.replace("冷","热").replace("多穿点","");
            // 输出strB=天热了
            /**
             * 获取压力数据
             */
            String replaceLISTYALI = LISTYALI.replace("currentTime: ,", "currentTime:" + currentTimeData + ",").replace(
                "upPre: ,", "upPre:" + upPreData + ",").replace("downPre: \n", "downPre:" + downPreData + "\n");
            String formatLISTYALI =replaceLISTYALI;

            /**
             * 获取结果表格数据
             */
            List<PreDataDto> preDataList = body.getPreDataList();
            String tableData = preDataList.stream().map(input -> String
                .format(LISTBIAOGE, input.getPreInfo(), input.getPreValue(), input.getPreTime(), input.getPreDrop()))
                .collect(Collectors.joining());

            //施工号
            String constructionNo1 = cylinderTestDataDto.getConstructionNo();
            //油缸编号
            String productNo = cylinderTestDataDto.getProductNo();
            //类型
            Integer oilCylinderType1 = cylinderTestDataDto.getOilCylinderType();
            //检测结果
            String errorMessage = cylinderTestDataDto.getErrorMessage();
            //检测员
            String userNo = cylinderTestDataDto.getUserNo();
            //实验时间
            LocalDateTime testTime = cylinderTestDataDto.getTestTime();
            String time = DateUtil.localDateTimeConvertStringHasUnderline(testTime);
            // 组装html
            String html = generateHtml(constructionNo1, productNo, oilCylinderType1, errorMessage, userNo, time,
                tableData,formatLISTYALI);

            //保存html的路径
            String remotePath = ACCESSORIES_REMOTE_PATH + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"))
                + File.separator + userNo + DateUtil.localDateTimeConvertString(testTime) + ".html";

            writeFile(html.getBytes(StandardCharsets.UTF_8), remotePath);

        }
    }

    private String generateHtml(String constructionNo1, String productNo, Integer oilCylinderType1, String errorMessage,
        String userNo, String time, String tableData,String formatLISTYALI) {
        OilcylinderEnum parse = OilcylinderEnum.parse(oilCylinderType1);

        String message;
        if (errorMessage != null) {
            message = "失败";
        } else {
            message = "成功";
        }
        //施工号 油缸编号 类型 检测结果
        String formatLISTGAIYAO = String.format(LISTGAIYAO, constructionNo1, productNo, parse.getTitle(), message);

        //检测员 实验时间
        String formatLISTJIANCE = String.format(LISTJIANCE, userNo, time);

        String start = "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "\n" + "\t<head>\n"
            + "\t\t<meta charset=\"UTF-8\">\n" + "\t\t<title>郑煤机推移千斤顶综合测试平台</title>\n"
            + "\t\t<link rel=\"icon\" href=\"static/img/title_icon.ico\" type=\"image/x-icon\">\n"
            + "\t\t<link rel=\"shortcut icon\" href=\"static/img/title_icon.ico\" type=\"image/x-icon\">\n"
            + "\t\t<link rel=\"stylesheet\" href=\"static/index.css\">\n"
            + "\t\t<script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"></script>\n" + "\t</head>\n"
            + "\t<body>\n" + "\t\t<div id=\"app\" class=\"content-wraper\">\n" + "\t\t\t<h2 class=\"title\">\n"
            + "\t\t\t\t<img src=\"static/img/logoMini.png\">\n" + "\t\t\t\t郑州煤矿机械集团\n" + "\t\t\t</h2>\n"
            + "\t\t\t<h3 class=\"title vice-title\">\n" + "\t\t\t\t油缸检测实验报告\n" + "\t\t\t</h3>\n" + "\t\t\t<!-- 摘要 -->";

        // return start + formatLISTGAIYAO + LISTBIAOGEPRE + tableData + LISTBIAOGESUFFIX + formatLISTJIANCE;
        return start + formatLISTGAIYAO + LISTBIAOGEPRE + tableData + LISTBIAOGESUFFIX + formatLISTJIANCE + formatLISTYALI;
    }

    private void writeFile(byte[] data, String path) {
        String pathValue = path.substring(0, path.lastIndexOf(File.separator) + 1);
        File remotePath = new File(pathValue);
        if (!remotePath.exists() && !remotePath.mkdirs()) {
            throw new RuntimeException(ExceptionEnum.FAIL.getMessage());
        }
        try {
            Files.write(Paths.get(path), data);
        } catch (IOException e) {
            throw new RuntimeException(ExceptionEnum.FAIL.getMessage());
        }
    }
}
